package com.sz.admin.system.controller;

import com.sz.admin.system.service.OcrRecognitionService;
import com.sz.core.common.entity.ApiResult;
import com.sz.core.common.enums.CommonResponseEnum;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardCopyOption;

/**
 * OCR识别测试控制器
 *
 * @author sz-admin
 * @since 2025-09-16
 */
@Tag(name = "OCR识别测试")
@RestController
@RequestMapping("/system/ocr")
@RequiredArgsConstructor
public class OcrTestController {

    private final OcrRecognitionService ocrRecognitionService;

    @Operation(summary = "测试OCR识别功能")
    @PostMapping("/test")
    public ApiResult<OcrRecognitionService.OcrResult> testOcr(@RequestParam("file") MultipartFile file) {
        try {
            // 创建临时文件
            Path tempFile = Files.createTempFile("ocr_test_", file.getOriginalFilename());
            
            try {
                // 将上传的文件保存到临时位置
                Files.copy(file.getInputStream(), tempFile, StandardCopyOption.REPLACE_EXISTING);
                
                // 调用OCR服务
                OcrRecognitionService.OcrResult result = ocrRecognitionService.recognizeText(tempFile.toFile());
                
                return ApiResult.success(result);
                
            } finally {
                // 清理临时文件
                try {
                    Files.deleteIfExists(tempFile);
                } catch (IOException e) {
                    // 忽略删除失败的情况
                }
            }
            
        } catch (Exception e) {
            return ApiResult.error(CommonResponseEnum.UNKNOWN.message("OCR测试失败: " + e.getMessage()));
        }
    }
}